package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 菜品接口业务层
 */
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper ;
    @Autowired
    private SetmealDishMapper setmealDishMapper ;
    @Autowired
    private SetmealMapper setmealMapper ;

    /**
     * 分页查询菜品
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        //初始化分页查询参数
        PageHelper.startPage(dishPageQueryDTO.getPage() , dishPageQueryDTO.getPageSize()) ;
        //执行分页查询
        Page<DishVO> page = dishMapper.page(dishPageQueryDTO) ;

        //构造查询结果
        Long total = page.getTotal() ;
        List<DishVO> dishVOList = page.getResult() ;

        PageResult pageResult = new PageResult(total , dishVOList) ;

        return pageResult ;
    }

    /**
     * 插入菜品和对应的口味信息
     *
     * @param dishDTO
     */
    @Override
    public void saveWithFlavors(DishDTO dishDTO) {
        //向菜品表中插入一条数据
        //菜品默认为停售状态 但是前端传过来了 status 参数 所以不用手动赋值
        Dish dish = new Dish() ;
        BeanUtils.copyProperties(dishDTO , dish);
        dishMapper.insert(dish);

        Long dishId = dish.getId();  //获得主键

        //向口味表中插入 n 条数据
        //获取菜品数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0 ) {
            //将集合中的菜品添加dishId
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            //向口味表中批量插入 n 条数据
            dishFlavorMapper.insertBatch(flavors) ;
        }

    }

    /**
     * 批量删除菜品数据
     *
     * @param ids
     */
    @Override
    public void deleteBatch(List<Long> ids) {
        //判断这组菜品中是否有菜品处于起售中 有的话就抛异常 终止这次请求
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                //有菜品位于起售中 不能删
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE) ;
            }
        }

        //判断这组菜品是否关联了套餐 有的话就抛异常
        //根据菜品 id 在菜品-套餐表中查套餐id集合 判断结果是否为 空
        List<Long> setmealIdsByDishIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIdsByDishIds != null && setmealIdsByDishIds.size() > 0) {
            //当前菜品关联了套餐 不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL) ;
        }

        //批量删除菜品信息
        dishMapper.deleteBatch(ids);

        //删除菜品对应的口味信息
        dishFlavorMapper.deleteByDishIds(ids);
    }

    /**
     * 修改菜品信息和对应的口味信息
     *
     * @param dishDTO
     */
    @Transactional
    @Override
    public void updateWithFlavors(DishDTO dishDTO) {
        //因为口味表的数据不好修改 所以这里先把该菜品的所有口味数据删除掉然后再重新添加
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        //重新插入口味表数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors.forEach(dishFlavor -> {
            dishFlavor.setDishId(dishDTO.getId());
        });
        if (flavors != null && flavors.size() > 0) {
            dishFlavorMapper.insertBatch(flavors);
        }

        //修改菜品信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO , dish);
        dishMapper.update(dish) ;
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {

        //查询菜品和对应的分类信息
        DishVO dishVO = dishMapper.getWithCategoryById(id);

        //获取菜品口味数据
        List<DishFlavor> flavorList = dishFlavorMapper.getByDishId(id) ;

        dishVO.setFlavors(flavorList);

        return dishVO ;
    }

    /**
     * 菜品的起售和停售
     *
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        //构造菜品对象
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);

        //如果是停售操作 则对应的套餐也要停售
        if (status == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            // select setmeal_id from setmeal_dish where dish_id in (?,?,?)
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> getByCategoryId(Long categoryId) {
        Dish d = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        //根据分类 id 查询菜品
        List<DishVO> dishList = dishMapper.getByCategoryId(d);
        //根据查出来的额菜品id再分别去查对应的口味信息
        dishList.forEach(dish -> {
            List<DishFlavor> flavorList = dishFlavorMapper.getByDishId(dish.getId());
            dish.setFlavors(flavorList);
        });
        return dishList;
    }
}
